package com.company.woye.Inventory.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.company.woye.Inventory.adapter.InventoryListviewAdapter;
import com.company.woye.Inventory.entity.BookBoxCallWMSEntity;
import com.company.woye.Inventory.entity.DetailsEntity;
import com.company.woye.Inventory.entity.InventotyAllBoxInfo;
import com.company.woye.Inventory.entity.SummarzingEntity;
import com.company.woye.MyApplication;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.lcl.adapter.LCLDetailListviewAdapter;
import com.company.woye.onpackage.entity.OutStateEntity;
import com.company.woye.utils.BaseRequest;
import com.company.woye.utils.DBUtil;
import com.company.woye.utils.DataUtils;
import com.company.woye.utils.ScannerManager;
import com.company.woye.utils.SharedPreferenceUtils;
import com.company.woye.utils.Toaster;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

import static com.company.woye.utils.BaseRequest.postJsonData;

/**
 * 库存信息查询
 */
public class InventoryActivity extends BaseActivity implements InventoryListviewAdapter.OnItemClick {
    @BindView(R.id.lv_inventory_summary)
    ListView summaryListView;
    @BindView(R.id.box_inventory_split_page)
    CheckBox box_inventory_split_page;

    @BindView(R.id.ll_inventory_summary)
    LinearLayout summaryLinearLayout;

    @BindView(R.id.tv_inventory_summary)
    TextView summaryTextView;

    @BindView(R.id.lv_inventory_detail)
    ListView detailListView;

    @BindView(R.id.ll_inventory_detail)
    LinearLayout detailLinearLayout;

    @BindView(R.id.tv_inventory_detail)
    TextView detailTextView;

    @BindView(R.id.lv_inventory_number)
    ListView numberListView;

    @BindView(R.id.ll_inventory_number)
    LinearLayout numberLinearLayout;

    @BindView(R.id.tv_checkout_box_num_show)
    TextView boxNumTextView;

    @BindView(R.id.tv_checkout_box_show)
    TextView boxTextView;

    @BindView(R.id.et_checkout_box_show)
    EditText boxEditView;
    @BindView(R.id.tv_inventory_num_actual)
    TextView tvInventoryNumActual;
    @BindView(R.id.tv_inventory_num_empty_not_small)
    TextView tvInventoryNumEmptyNotSmall;
    @BindView(R.id.tv_inventory_num_empty_has_small)
    TextView tvInventoryNumEmptyHasSmall;
    @BindView(R.id.tv_inventory_search)
    TextView tvInventorySearch;
    @BindView(R.id.tv_inventory_dept)
    TextView tvInventoryDept;
    @BindView(R.id.tv_inventory_factory)
    TextView tvInventoryFactory;
    @BindView(R.id.ed_inventory_worker)
    EditText edInventoryWorker;
    @BindView(R.id.sp_on_package_material_type)
    Spinner sp_on_package_material_type;
    @BindView(R.id.ed_inventory_contract_no)
    EditText edInventoryContractNo;
    @BindView(R.id.ed_inventory_PO)
    EditText edInventoryPO;
    @BindView(R.id.ed_inventory_single_num)
    EditText edInventorySingleNum;
    @BindView(R.id.ed_inventory_order_num)
    EditText edInventoryOrderNum;
    @BindView(R.id.ed_inventory_color)
    EditText edInventoryColor;
    @BindView(R.id.ed_inventory_box_num)
    EditText edInventoryBoxNum;
    @BindView(R.id.ed_inventory_size)
    EditText edInventorySize;
    @BindView(R.id.sp_inventory_out_state)
    Spinner edInventoryOutState;
    @BindView(R.id.tv_inventory_num_total)
    TextView tv_inventory_num_total;
    @BindView(R.id.bt_checkout_box_show)
    Button btCheckoutBoxShow;
    @BindView(R.id.admin)
    RadioButton admin;
    @BindView(R.id.tech)
    RadioButton tech;
    @BindView(R.id.rg_checkout)
    RadioGroup rgCheckout;
    @BindView(R.id.ll_inventory_bottom_bar_code)
    LinearLayout llInventoryBottomBarCode;
    @BindView(R.id.tv_inventory_clear_box)
    TextView tvInventoryClearBox;
    @BindView(R.id.tv_inventory_box_internal_num)
    TextView tvInventoryBoxInternalNum;
    @BindView(R.id.tv_inventory_box_internal_num_show)
    TextView tvInventoryBoxInternalNumShow;
    @BindView(R.id.tv_inventory_out_bound)
    TextView tvInventoryOutBound;
    @BindView(R.id.tv_inventory_in_bound)
    TextView tvInventoryInBound;
    @BindView(R.id.tv_checkout_box_num)
    TextView tvCheckoutBoxNum;
    @BindView(R.id.tv_checkout_box)
    TextView tvCheckoutBox;
    @BindView(R.id.cb_all)
    CheckBox cb_all;
    @BindView(R.id.tv_station)
    TextView tvStation;
    @BindView(R.id.linerPageInfo)
    LinearLayout linerPageInfo;
    @BindView(R.id.tv_prior)
    TextView tv_prior;
    @BindView(R.id.tv_next)
    TextView tv_next;
    @BindView(R.id.tv_pageinfo)
    TextView tv_pageinfo;


    private String deptName = "", cJname = "", LoginUserNo = "", FormType = "", OperType = "", lsxName = "";
    private int pageSize=30,pageIndex=-1,pageCount=-1;
    private String StationNo = "";
    private String TAG = getClass().getSimpleName();
    private JSONArray detailJsonarrayarray;
    private static final int MSG_CallAgvResult = 9008;
    private static final int MSG_GetAgvCallInfo = 9009;
    private static final int MSG_CallAgvBoxOutResult = 8009;
    private final int MSG_waitOutCall = 7006;
    public static final int MSG_ERRMSG = 9999;
    String BatchID=UUID.randomUUID().toString().toUpperCase();
    private String isBind = "1";
    private List<SummarzingEntity> summarzingEntities;
    private ScannerManager scannerManager;
    private InventoryListviewAdapter inventoryListviewAdapter;


    private final int SEARCHBOXINFO = 101;
    private final int SEARCHSUMMAR = 102;
    private final int SearchBarCodeInFo = 103;
    private final int CLEARBOX = 104;
    private final int INBOUNDCHECK = 105;
    private final int OUTBOUND = 106;
    private final int STOPOUTBOUND = 107;
    private final int RETURNOUTBOUND = 108;
    private final int SEARCHDETAIL = 109;
    private String TaskId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_inventory;
    }

    @Override
    public void initView() {
        linerPageInfo.setVisibility(View.GONE);
        deptName = MyApplication.Bbm;
        cJname = MyApplication.CjName;
        LoginUserNo = MyApplication.curLoginUserNo;
        lsxName = MyApplication.DepartMent;
        FormType = TAG;
        if (((String) SharedPreferenceUtils.getData(sharedPreferences, "nowGongWei", "0")).equals("0")) {
            StationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "leftGongWei", "");
        } else {
            StationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "rightGongWei", "");
        }
        tvInventoryDept.setText(deptName);
        tvInventoryFactory.setText(cJname);
        tvStation.setText("工位号:"+StationNo);


        boxEditView.setInputType(InputType.TYPE_NULL);
        boxEditView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boxEditView.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(boxEditView, InputMethodManager.SHOW_FORCED);
            }
        });
        boxEditView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    Log.e("Debug", "-----------------------------Debug-----------------------------");
                    //System.out.println(event);
                    if ((event.getAction() == KeyEvent.ACTION_UP) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        ScanBarcode();
                        return true;
                    }
                }
                return false;
            }
        });
        boxEditView.requestFocus();
        boxEditView.requestFocusFromTouch();
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                Log.d(TAG, "code= " + code);
                String nowCode = dealCode(code).trim();
                boxEditView.setText(nowCode);
                ScanBarcode();
            }
        },boxEditView.getContext());

        summaryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                detailTextView.setTextColor(getResources().getColor(R.color.blue));
                summaryTextView.setTextColor(getResources().getColor(R.color.darkGray));
                detailLinearLayout.setVisibility(View.VISIBLE);
                summaryLinearLayout.setVisibility(View.GONE);
                String BoxNo = summarzingEntities.get(i).getBoxNo();
                String sql = "EXEC AGV_Stock_StockSearch @FormType='" + FormType + "',@BoxNo='" + BoxNo + "',@OperType='StockSearchMX',@UserNo='" + LoginUserNo + "'";
                ReadSQLData(sql, SEARCHDETAIL);
            }
        });
        //summaryListView.setAdapter(new InventoryListviewAdapter(this));
//        detailListView.setOnItemClickListener((parent, view, position, id) -> {
//            numberLinearLayout.setVisibility(View.VISIBLE);
//            summaryLinearLayout.setVisibility(View.INVISIBLE);
//            String BoxNo=summarzingEntities.get(position).getBoxNo();
//            String sql="EXEC AGV_Stock_StockSearch @FormType='"+FormType+"',@BoxNo='"+BoxNo+"',@OperType='StockSearchMX',@UserNo='"+LoginUserNo+"'";
//            ReadSQLData(sql,SEARCHDETAIL);
//        });
        //全选
        cb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (summarzingEntities != null && summarzingEntities.size() > 0) {
                    if (b) {
                        for (int i = 0; i < summarzingEntities.size(); i++) {
                            summarzingEntities.get(i).setIsChoose(true);
                        }
                    } else {
                        for (int i = 0; i < summarzingEntities.size(); i++) {
                            summarzingEntities.get(i).setIsChoose(false);
                        }
                    }
                    if (inventoryListviewAdapter != null) {
                        inventoryListviewAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    //保留英文和数字
    private String dealCode(String code) {
        return code.replaceAll("[^a-zA-Z0-9]", "");
    }

    private void ScanBarcode() {
        boxEditView.setText("");
        String barCode = boxEditView.getText().toString();
        String BoxNo = boxNumTextView.getText().toString();
        if (!TextUtils.isEmpty(barCode)) {
            /**
             * EXEC AGV_Stock_StockSearch @FormType='',@Barcode='006303443426',@BoxNo='O040800001',@IsBind='1',@OperType='ScanBarcode',@UserNo=''
             */
            String sqlSearchCode = "EXEC AGV_Stock_StockSearch @FormType='" + FormType + "',@Barcode='" + barCode + "',@BoxNo='" + BoxNo + "',@IsBind='" + isBind + "',@OperType='ScanBarcode',@UserNo='" + LoginUserNo + "'";
            ReadSQLData(sqlSearchCode, SearchBarCodeInFo);
        } else {
            Toast.makeText(InventoryActivity.this, "请先扫描或者输入条码", Toast.LENGTH_LONG).show();
        }
    }

    @OnClick({R.id.admin, R.id.tech, R.id.tv_inventory_search, R.id.iv_inventory_back, R.id.tv_inventory_back, R.id.tv_inventory_summary, R.id.tv_inventory_detail,
            R.id.tv_inventory_check_num, R.id.tv_inventory_in_bound, R.id.tv_inventory_out_bound, R.id.tv_inventory_clear_box,
            R.id.bt_checkout_box_show,R.id.tv_prior,R.id.tv_next})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.tv_prior:
                if (pageIndex>1) {
                    pageIndex--;
                    queryData(pageSize, pageIndex);
                }else Toaster.showLong(InventoryActivity.this,"已是第一页");
                break;
            case R.id.tv_next:
                if (pageIndex+1<pageCount) {
                    pageIndex++;
                    queryData(pageSize,pageIndex);
                } else Toaster.showLong(InventoryActivity.this,"已是最后一页");
                break;

            case R.id.tv_inventory_back:
            case R.id.iv_inventory_back:
                finish();
                break;
            //查询
            case R.id.tv_inventory_search:
                hideIM(edInventorySize);
                //--库存查询 仓库箱汇总
                //EXEC AGV_Stock_StockSearch @FormType='',@bbm='',@cj_name='',@Operator='',@OrderNo='',@StyleNo='',@PO='',@DBH=''
                // ,@Bw='',@BoxNo='',@TXM='',@OutState='',@OperType='StockBoxSum',@UserNo=''
                pageSize=30;
                pageIndex=-1;
                BatchID=UUID.randomUUID().toString().toUpperCase();
                queryData(pageSize,pageIndex);

                break;
            case R.id.tv_inventory_summary:
                summaryTextView.setTextColor(getResources().getColor(R.color.blue));
                detailTextView.setTextColor(getResources().getColor(R.color.darkGray));
                detailLinearLayout.setVisibility(View.GONE);
                summaryLinearLayout.setVisibility(View.VISIBLE);
                break;
//            case R.id.tv_inventory_detail:
//                detailTextViewOnClick();
//                break;
            case R.id.tv_inventory_check_num:
                checkNumTextViewOnClick();
                break;
            //入库
            case R.id.tv_inventory_in_bound:
                /**
                 * Exec AGV_Stock_StockCallWMS @FormType='',@DepSiteNo='D00M3001',@BoxNo='O040800001',@BoxType='入库',@TaskID='4755106c-ac43-4bf5-afa8-0131cfe942df',@IsEmpty='2',@OperType='StockInCallWMS',@UserNo='000000'
                 * 先判断是不是空箱
                 */
                String BoxNo2 = boxNumTextView.getText().toString();
                if (!TextUtils.isEmpty(BoxNo2)) {
                    TaskId = UUID.randomUUID().toString();
                    String sqlInBound = "Exec AGV_Stock_StockCallWMS @FormType='" + FormType + "',@DepSiteNo='" + StationNo
                            + "',@BoxNo='" + BoxNo2 + "',@BoxType='入库',@TaskID='" + TaskId + "',@IsEmpty='2'," +
                            "@OperType='StockInCallWMS',@UserNo='" + LoginUserNo + "'";
                    ReadSQLData(sqlInBound, INBOUNDCHECK);

                } else {
                    Toast.makeText(InventoryActivity.this, "请先扫描或者输入箱码", Toast.LENGTH_LONG).show();
                }

                break;
            //出库
            case R.id.tv_inventory_out_bound:
                boolean haveNoOutStore = false;
                List<SummarzingEntity> addsummarzingEntityList = new ArrayList<>();
                if (summarzingEntities != null && summarzingEntities.size() > 0) {
                    for (int i = 0; i < summarzingEntities.size(); i++) {
                        if (summarzingEntities.get(i).getIsChoose()) {
                            haveNoOutStore = true;
                            addsummarzingEntityList.add(summarzingEntities.get(i));
                        }
                    }
                    if (!haveNoOutStore) {
                        Toaster.showLong(InventoryActivity.this, "请先勾选要出库的行");
                        return;
                    }
                    /**
                     * Exec AGV_Stock_StockCallWMS @FormType='',@DepSiteNo='D00M3001',@BoxType='出库',
                     * @TaskID='4755106c-ac43-4bf5-afa8-0131cfe942df',@OperType='StockOutCallWMS',@UserNo='000000'
                     * ,@OutBoxNos='O040800002,O040800003'
                     */
                    List<String> OutBoxNos = new ArrayList();
                    for (int i = 0; i < addsummarzingEntityList.size(); i++) {
                        OutBoxNos.add(addsummarzingEntityList.get(i).getBoxNo());
                    }

                    TaskId = UUID.randomUUID().toString();
                    String Sql = "Exec AGV_Stock_StockCallWMS @FormType='" + FormType + "',@DepSiteNo='" + StationNo + "',@BoxType='出库'" +
                            ",@TaskID='" + TaskId + "',@OperType='StockOutCallWMS',@UserNo='" + LoginUserNo + "',@OutBoxNos='" + DataUtils.listToString(OutBoxNos) + "'";
                    ReadSQLData(Sql, OUTBOUND);


                } else {
                    Toaster.showLong(InventoryActivity.this, "列表为空");
                }
                //  showPopupWindow();
                break;
            case R.id.tv_inventory_clear_box:
                /**
                 * EXEC AGV_Stock_StockSearch @FormType='',@BoxNo='O040800001',@OperType='ClearBarcode',@UserNo=''
                 */
                String BoxNo1 = boxNumTextView.getText().toString();
                if (!TextUtils.isEmpty(BoxNo1)) {
                    String sqlClear = "EXEC AGV_Stock_StockSearch @FormType='',@BoxNo='" + BoxNo1 + "',@OperType='ClearBarcode',@UserNo='" + LoginUserNo + "'";
                    ReadSQLData(sqlClear, CLEARBOX);
                } else {
                    Toast.makeText(InventoryActivity.this, "请先扫描或者输入箱码", Toast.LENGTH_LONG).show();
                }

//                boxNumTextView.setText("");
//                boxTextView.setText("");
                break;
            case R.id.admin:
                isBind = "1";
                //ScanBarcode();
                break;
            case R.id.tech:
                isBind = "0";
                //ScanBarcode();
                break;
            //扫描
            case R.id.bt_checkout_box_show:
                ScanBarcode();
                break;
        }
    }

    private void queryData(int pageSize, int pageIndex) {
        String tj="";
        if (box_inventory_split_page.isChecked()) tj=",@AutoSplit=1";
        String sql = "EXEC AGV_Stock_StockSearch  @MaterielType ='" + sp_on_package_material_type.getSelectedItem() + "',@FormType='" + FormType + "',@bbm='" + tvInventoryDept.getText().toString()
                + "',@cj_name='" + tvInventoryFactory.getText().toString() + "',@Operator='" + edInventoryWorker.getText().toString().trim()
                + "',@OrderNo='" + edInventoryOrderNum.getText().toString().trim() + "',@StyleNo='" + edInventoryContractNo.getText().toString().trim()
                + "',@PO='" + edInventoryPO.getText().toString().trim() + "',@DBH='" + edInventorySingleNum.getText().toString() + "',@Color='" +
                "" + edInventoryColor.getText().toString().trim() + "',@BoxNo='" + edInventoryBoxNum.getText().toString()
                + "',@Size='" + edInventorySize.getText().toString().trim() + "',@OutState='" + edInventoryOutState.getSelectedItem()
                + "',@OperType='StockBoxSum',@UserNo='" + LoginUserNo +"',@BatchID='"+BatchID+"',@PageIndex="+pageIndex+",@PageSize="+pageSize+tj;
        ReadSQLData(sql, SEARCHBOXINFO);
    }

    private void ReadSQLData(String sql, int type) {
        System.out.print("----存储过程:" + sql + "\r\n");
        try {
            detailJsonarrayarray = new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        boxEditView.requestFocus();
        boxEditView.requestFocusFromTouch();
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    /**
                     * [{"RoleName":"管理员"},{"RoleName":"调度"},{"RoleName":"装框操作"},{"RoleName":"物流运转"},{"RoleName":"试装箱"}]
                     */
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(sql);
                    System.out.print("--type:" + type + " --返回结果：" + jsonArray);
                    if (jsonArray != null && jsonArray.length() > 0) {
                        if (jsonArray.optJSONObject(0).has("SQLExcept")) {
                            Message message = new Message();
                            message.what = MSG_ERRMSG;
                            Bundle bundle = new Bundle();
                            bundle.putString("Hint", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            message.setData(bundle);
                            handler.sendMessage(message);
                        } else {
                            detailJsonarrayarray = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = type;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                    } else {
                        Message msg = new Message();
                        msg.what = MSG_ERRMSG;
                        Bundle bundle = new Bundle();
                        bundle.putString("Hint", "未返回任何内容！");
                        msg.setData(bundle);
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = MSG_ERRMSG;
                    Bundle bundle = new Bundle();
                    bundle.putString("Hint", e.getMessage());
                    msg.setData(bundle);
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ERRMSG:
                    //提示提交完成，需确认;
                    Bundle bundle1 = msg.getData();
                    String resultMsg = bundle1.getString("Hint");
                    // 创建对话框
                    AlertDialog alertDialog = new AlertDialog.Builder(tvInventoryDept.getContext())
                            .setTitle("系统提示").setMessage(resultMsg)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).create();
                    alertDialog.show(); // 显示对话框
                    break;
                //获取箱数信息
                case SEARCHBOXINFO:
                    if (detailJsonarrayarray != null && detailJsonarrayarray.length() > 0) {
                        Gson gson = new Gson();
                        List<InventotyAllBoxInfo> list = new ArrayList<>();
                        list.addAll(gson.fromJson(String.valueOf(detailJsonarrayarray), new TypeToken<List<InventotyAllBoxInfo>>() {
                        }.getType()));
                        if (list.size() > 0) {
                            tvInventoryNumActual.setText("仓库实箱" + list.get(0).getBoxNoFullNum());
                            tvInventoryNumEmptyNotSmall.setText("空箱（不含小）" + list.get(0).getBoxNoEmptyNum());
                            tvInventoryNumEmptyHasSmall.setText("空箱（含小）" + list.get(0).getBoxNoEmptySmallNum());
                            tv_inventory_num_total.setText("总" + list.get(0).getBoxNoNum() + "箱");
                            if (list.get(0).getPageCount()>0){
                                linerPageInfo.setVisibility(View.VISIBLE);
                                tv_pageinfo.setText(list.get(0).getPageInfo());
                                pageIndex=list.get(0).getPageIndex();
                                pageSize=list.get(0).getPageSize();
                                pageCount=list.get(0).getPageCount();
                            } else linerPageInfo.setVisibility(View.GONE);
                        }
                    } else {
                        Toaster.showLong(InventoryActivity.this, "没有返回信息");
                    }

                    //汇总查询
                    searchSummarizing();
                    break;
                //获取汇总信息
                case SEARCHSUMMAR:
                    if (detailJsonarrayarray != null && detailJsonarrayarray.length() > 0) {
                        System.out.println("detailJsonarrayarray：" + detailJsonarrayarray.toString());
                        Gson gson = new Gson();
                        summarzingEntities = new ArrayList<>();
                        summarzingEntities.addAll(gson.fromJson(String.valueOf(detailJsonarrayarray), new TypeToken<List<SummarzingEntity>>() {
                        }.getType()));
                        if (summarzingEntities.size() > 0) {
                            for (int i = 0; i < summarzingEntities.size(); i++) {
                                SummarzingEntity summarzingEntity = summarzingEntities.get(i);
                                System.out.println(i + "-OrderNo：" + summarzingEntity.getOrderNo() + " StyleNo：" + summarzingEntity.getStyleNo());
                            }
                            inventoryListviewAdapter = new InventoryListviewAdapter(InventoryActivity.this, summarzingEntities, InventoryActivity.this);
                            summaryListView.setAdapter(inventoryListviewAdapter);
                        }
                    } else {
                        Toaster.showLong(InventoryActivity.this, "没有返回信息");
                    }

                    break;
                //获取扫码信息
                case SearchBarCodeInFo:
                    if (detailJsonarrayarray != null && detailJsonarrayarray.length() > 0) {
                        try {

                            if (detailJsonarrayarray.optJSONObject(0).has("BoxNo"))
                                boxNumTextView.setText(detailJsonarrayarray.optJSONObject(0).getString("BoxNo"));
                            if (detailJsonarrayarray.optJSONObject(0).has("TXM"))
                                boxTextView.setText(detailJsonarrayarray.optJSONObject(0).getString("TXM"));
                            if (detailJsonarrayarray.optJSONObject(0).has("BoxCountNum"))
                                tvInventoryBoxInternalNumShow.setText(detailJsonarrayarray.optJSONObject(0).getString("BoxCountNum"));
                            if (detailJsonarrayarray.optJSONObject(0).has("ResultInfo"))
                                Toaster.showLong(InventoryActivity.this, detailJsonarrayarray.optJSONObject(0).getString("ResultInfo"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toaster.showLong(InventoryActivity.this, "没有返回信息");
                    }
                    break;
                //清空箱子
                case CLEARBOX:
                    if (detailJsonarrayarray != null && detailJsonarrayarray.length() > 0) {
                        try {
                            if (detailJsonarrayarray.optJSONObject(0).has("ResultInfo")) {
                                Toaster.showLong(InventoryActivity.this, detailJsonarrayarray.optJSONObject(0).getString("ResultInfo"));
                                if (detailJsonarrayarray.optJSONObject(0).getString("ResultInfo").equals("箱号清除成功")) {
                                    tvInventoryBoxInternalNumShow.setText("");
                                    boxNumTextView.setText("");
                                    boxEditView.setText("");
                                    boxTextView.setText("");
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toaster.showLong(InventoryActivity.this, "没有返回信息");
                    }
                    break;
                //入库  先判断箱子里是否有东西  有的话直接调用入库 没有的话调用空箱入库
                case INBOUNDCHECK:
                    if (detailJsonarrayarray != null && detailJsonarrayarray.length() > 0) {
                        try {
                            if (detailJsonarrayarray.optJSONObject(0).has("IsEmpty")) {
                                if (detailJsonarrayarray.optJSONObject(0).getString("IsEmpty").equals("1")) {
                                    inBoundTextViewOnClick();
                                } else {
                                    //直接入库
                                    if ((detailJsonarrayarray != null) && (detailJsonarrayarray.length() > 0)) {
                                        String bookNo = "", boxNo = "", boxType = "", depSiteNo = "", destSiteNo = "", isEmpty = "", boxHeight = "", boxVolume = "", DestOrderNo = "", taskID = "", ResultInfo1 = "";
                                        if (detailJsonarrayarray.optJSONObject(0).has("bookNo"))
                                            bookNo = detailJsonarrayarray.optJSONObject(0).getString("bookNo");
                                        if (detailJsonarrayarray.optJSONObject(0).has("boxNo"))
                                            boxNo = detailJsonarrayarray.optJSONObject(0).getString("boxNo");
                                        if (detailJsonarrayarray.optJSONObject(0).has("boxType"))
                                            boxType = detailJsonarrayarray.optJSONObject(0).getString("boxType");
                                        if (detailJsonarrayarray.optJSONObject(0).has("depSiteNo"))
                                            depSiteNo = detailJsonarrayarray.optJSONObject(0).getString("depSiteNo");
                                        if (detailJsonarrayarray.optJSONObject(0).has("destSiteNo"))
                                            destSiteNo = detailJsonarrayarray.optJSONObject(0).getString("destSiteNo");
                                        if (detailJsonarrayarray.optJSONObject(0).has("isEmpty"))
                                            isEmpty = detailJsonarrayarray.optJSONObject(0).getString("isEmpty");
                                        if (detailJsonarrayarray.optJSONObject(0).has("boxHeight"))
                                            boxHeight = detailJsonarrayarray.optJSONObject(0).getString("boxHeight");
                                        if (detailJsonarrayarray.optJSONObject(0).has("boxVolume"))
                                            boxVolume = detailJsonarrayarray.optJSONObject(0).getString("boxVolume");
                                        if (detailJsonarrayarray.optJSONObject(0).has("DestOrderNo"))
                                            DestOrderNo = detailJsonarrayarray.optJSONObject(0).getString("DestOrderNo");
                                        if (detailJsonarrayarray.optJSONObject(0).has("TaskID"))
                                            taskID = detailJsonarrayarray.optJSONObject(0).getString("TaskID");
                                        if (detailJsonarrayarray.optJSONObject(0).has("ResultInfo"))
                                            ResultInfo1 = detailJsonarrayarray.optJSONObject(0).getString("ResultInfo");
                                        callAgv(bookNo, boxNo, boxType, depSiteNo, destSiteNo, isEmpty, boxHeight, boxVolume, DestOrderNo, taskID);
                                    }
                                }
                            } else {
                                if ((detailJsonarrayarray != null) && (detailJsonarrayarray.length() > 0)) {
                                    String bookNo = "", boxNo = "", boxType = "", depSiteNo = "", destSiteNo = "", isEmpty = "", boxHeight = "", boxVolume = "", DestOrderNo = "", taskID = "", ResultInfo1 = "";
                                    if (detailJsonarrayarray.optJSONObject(0).has("bookNo"))
                                        bookNo = detailJsonarrayarray.optJSONObject(0).getString("bookNo");
                                    if (detailJsonarrayarray.optJSONObject(0).has("boxNo"))
                                        boxNo = detailJsonarrayarray.optJSONObject(0).getString("boxNo");
                                    if (detailJsonarrayarray.optJSONObject(0).has("boxType"))
                                        boxType = detailJsonarrayarray.optJSONObject(0).getString("boxType");
                                    if (detailJsonarrayarray.optJSONObject(0).has("depSiteNo"))
                                        depSiteNo = detailJsonarrayarray.optJSONObject(0).getString("depSiteNo");
                                    if (detailJsonarrayarray.optJSONObject(0).has("destSiteNo"))
                                        destSiteNo = detailJsonarrayarray.optJSONObject(0).getString("destSiteNo");
                                    if (detailJsonarrayarray.optJSONObject(0).has("isEmpty"))
                                        isEmpty = detailJsonarrayarray.optJSONObject(0).getString("isEmpty");
                                    if (detailJsonarrayarray.optJSONObject(0).has("boxHeight"))
                                        boxHeight = detailJsonarrayarray.optJSONObject(0).getString("boxHeight");
                                    if (detailJsonarrayarray.optJSONObject(0).has("boxVolume"))
                                        boxVolume = detailJsonarrayarray.optJSONObject(0).getString("boxVolume");
                                    if (detailJsonarrayarray.optJSONObject(0).has("DestOrderNo"))
                                        DestOrderNo = detailJsonarrayarray.optJSONObject(0).getString("DestOrderNo");
                                    if (detailJsonarrayarray.optJSONObject(0).has("ResultInfo"))
                                        ResultInfo1 = detailJsonarrayarray.optJSONObject(0).getString("ResultInfo");
                                    if (detailJsonarrayarray.optJSONObject(0).has("TaskID"))
                                        taskID = detailJsonarrayarray.optJSONObject(0).getString("TaskID");
                                    callAgv(bookNo, boxNo, boxType, depSiteNo, destSiteNo, isEmpty, boxHeight, boxVolume, DestOrderNo, taskID);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toaster.showLong(InventoryActivity.this, "没有返回信息");
                    }
                    break;
                //实箱入库
                case MSG_CallAgvResult:
                    System.out.println("MSG_CallAgvResult:" + MSG_CallAgvResult);
                    if (msg.arg1 == BaseRequest.HAND_REQUEST_FAILURE) {
                        Toaster.showLong(InventoryActivity.this, "请求失败：" + msg.obj.toString());
                        return;
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.has("status") && jsonObject.get("status").equals("0")) {
                            Toaster.showLong(InventoryActivity.this, "呼叫成功");
                        } else if (jsonObject.has("status") && jsonObject.get("status").equals("1")) {
                            Toaster.showLong(InventoryActivity.this, "呼叫失败：" + jsonObject.get("errorinfo"));
                        } else {
                            if (jsonObject.has("errorinfo")) {
                                Toaster.showLong(InventoryActivity.this, "呼叫失败：" + jsonObject.get("errorinfo"));
                            } else {
                                Toaster.showLong(InventoryActivity.this, "呼叫失败");
                            }
                        }
                    } catch (JSONException e) {
                        Toaster.showLong(InventoryActivity.this, "解析失败");
                    }
                    TransAgvCallInfo(msg.obj.toString(), "StockInCallWMS");
                    break;
                //出库回调
                case MSG_CallAgvBoxOutResult:
                    System.out.println("MSG_CallAgvBoxOutResult:" + MSG_CallAgvBoxOutResult);
                    if (msg.arg1 == BaseRequest.HAND_REQUEST_FAILURE) {
                        System.out.println("MSG_CallAgvBoxOutResult:" + 1);
                        Toaster.showLong(InventoryActivity.this, "请求失败：" + msg.obj.toString());
                        return;
                    }
                    try {
                        System.out.println("MSG_CallAgvBoxOutResult:" + 2);
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.has("status") && jsonObject.get("status").equals("0")) {
                            Toaster.showLong(InventoryActivity.this, "呼叫成功");
                        } else if (jsonObject.has("status") && jsonObject.get("status").equals("1")) {
                            Toaster.showLong(InventoryActivity.this, "呼叫失败：" + jsonObject.get("errorinfo"));
                        } else {
                            if (jsonObject.has("errorinfo")) {
                                Toaster.showLong(InventoryActivity.this, "呼叫失败：" + jsonObject.get("errorinfo"));
                            } else {
                                Toaster.showLong(InventoryActivity.this, "呼叫失败");
                            }
                        }
                        System.out.println("MSG_CallAgvBoxOutResult:" + 3);
                    } catch (JSONException e) {
                        Toaster.showLong(InventoryActivity.this, "解析失败");
                    }
                    System.out.println("MSG_CallAgvBoxOutResult:" + 4);
                    TransAgvCallInfo(msg.obj.toString(), "StockOutCallWMS");
                    System.out.println("MSG_CallAgvBoxOutResult:" + 5);
                    break;
                //实箱入库回调
                case MSG_GetAgvCallInfo:
                    System.out.println("MSG_GetAgvCallInfo:Enter");
                    //清除界面显示并刷新箱号
                    break;
                //出库
                case OUTBOUND:
                    if (detailJsonarrayarray != null && detailJsonarrayarray.length() > 0) {
                        Gson gson = new Gson();
                        List<BookBoxCallWMSEntity> bookBoxCallWMSEntities = gson.fromJson(String.valueOf(detailJsonarrayarray), new TypeToken<List<BookBoxCallWMSEntity>>() {
                        }.getType());
                        //呼叫WMS
                        bookBoxCallWMS(bookBoxCallWMSEntities);
                    } else {
                        Toaster.showLong(InventoryActivity.this, "没有返回信息");
                    }
                    break;
                //暂停出库
                case STOPOUTBOUND:
                    if (detailJsonarrayarray != null && detailJsonarrayarray.length() > 0) {
                        Gson gson = new Gson();
                        List<OutStateEntity> CallBackEntity = gson.fromJson(String.valueOf(detailJsonarrayarray), new TypeToken<List<OutStateEntity>>() {
                        }.getType());
                        if (CallBackEntity != null && CallBackEntity.size() > 0) {
                            callWaitOut(CallBackEntity.get(0));
                        }

                    }
                    break;
                //暂停出库
                case MSG_waitOutCall:
                    String SqlComm = "Exec AGV_Check_CheckBagCallWMS_Trans  @OperType='" + "暂停出库" + "',@TaskID='" + TaskId + "',@ReturnInfo='" + msg.obj + "',@UserNo='" + LoginUserNo + "'";
                    ReadSQLData(SqlComm, MSG_GetAgvCallInfo);
                    break;
                //恢复出库
                case RETURNOUTBOUND:
                    if (detailJsonarrayarray != null && detailJsonarrayarray.length() > 0) {
                        Gson gson = new Gson();
                        List<BookBoxCallWMSEntity> bookBoxCallWMSEntityList = gson.fromJson(String.valueOf(detailJsonarrayarray), new TypeToken<List<BookBoxCallWMSEntity>>() {
                        }.getType());
                        //呼叫WMS
                        bookBoxCallWMS(bookBoxCallWMSEntityList);
                    }
                    break;
                //明细
                case SEARCHDETAIL:
                    if (detailJsonarrayarray != null && detailJsonarrayarray.length() > 0) {
                        Gson gson = new Gson();
                        List<DetailsEntity> detailsEntities = gson.fromJson(String.valueOf(detailJsonarrayarray), new TypeToken<List<DetailsEntity>>() {
                        }.getType());
                        if (detailsEntities != null && detailsEntities.size() > 0) {
                            detailListView.setAdapter(new LCLDetailListviewAdapter(InventoryActivity.this, detailsEntities));
                        }
                    } else {
                        Toaster.showLong(InventoryActivity.this, "没有返回信息");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void callWaitOut(OutStateEntity outStateEntity) {
        OutStateEntity outStateEntity1 = null;
        if (outStateEntity != null) {
            outStateEntity1 = new OutStateEntity(outStateEntity.getSiteNo(), outStateEntity.getOrderNo(), outStateEntity.getOrderOperate(), outStateEntity.getUserNo());
            String json = new Gson().toJson(outStateEntity1);
            if (MyApplication.UrlWms.isEmpty()) {
                Toast.makeText(InventoryActivity.this, "请先输入WMS地址", Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println(json);
            postJsonData(MyApplication.UrlWms + "/OutTaskUpdate", json, handler, MSG_waitOutCall);
        }
    }

    private void bookBoxCallWMS(List<BookBoxCallWMSEntity> bookBoxLists) {
        if (bookBoxLists != null && bookBoxLists.size() > 0) {
            String json = new Gson().toJson(bookBoxLists);
            if (MyApplication.UrlWms.isEmpty()) {
                Toast.makeText(InventoryActivity.this, "请先输入WMS地址", Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println(json);
            postJsonData(MyApplication.UrlWms + "/BookBoxOut", json, handler, MSG_CallAgvBoxOutResult);
        }
    }

    private void TransAgvCallInfo(String ReturnInfo, String operType) {
        System.out.println("Enter GetAgvCallInfo");
        String SqlComm = "Exec AGV_Check_CutInCallWMS_Trans @OperType='" + operType + "',@TaskID='" + TaskId + "',@ReturnInfo='" + ReturnInfo + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        Log.e(TAG, SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm, MSG_GetAgvCallInfo);
    }

    //呼叫AGV
    private void callAgv(String bookNo, String boxNo, String boxType, String depSiteNo, String destSiteNo, String isEmpty,
                         String boxHeight, String boxVolume, String DestOrderNo, String TaskID) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("BookNo", bookNo);
            jsonObject.put("BoxNo", boxNo);
            jsonObject.put("BoxType", boxType);
            jsonObject.put("DepSiteNo", depSiteNo);
            jsonObject.put("DestSiteNo", destSiteNo);
            jsonObject.put("IsEmpty", isEmpty);
            jsonObject.put("BoxHeight", boxHeight);
            jsonObject.put("BoxVolume", boxVolume);
            jsonObject.put("DestOrderNo", DestOrderNo);
            jsonObject.put("TaskID", TaskID);
            jsonObject.put("UserNo", MyApplication.curLoginUserNo);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        System.out.println(jsonObject.toString());
        postJsonData(MyApplication.UrlWms + "/BoxPackage", jsonObject.toString(), handler, MSG_CallAgvResult);
    }

    private void searchSummarizing() {
        System.out.println("searchSummarizing start");
        String tj="";
        if (box_inventory_split_page.isChecked()) tj=",@AutoSplit=1";
        //--库存查询 汇总
        //--EXEC AGV_Stock_StockSearch @FormType='',@bbm='',@cj_name='',@Operator='',@OrderNo='',@StyleNo=''
        // ,@PO='',@DBH='',@Bw='',@BoxNo='',@TXM='',@OutState='',@OperType='StockSearch',@UserNo=''
        String sql = "EXEC AGV_Stock_StockSearch @MaterielType ='" + sp_on_package_material_type.getSelectedItem() + "',@FormType='" + FormType + "',@bbm='" + tvInventoryDept.getText().toString()
                + "',@cj_name='" + tvInventoryFactory.getText().toString() + "',@Operator='" + edInventoryWorker.getText().toString().trim()
                + "',@OrderNo='" + edInventoryOrderNum.getText().toString().trim() + "',@StyleNo='" + edInventoryContractNo.getText().toString().trim()
                + "',@PO='" + edInventoryPO.getText().toString().trim() + "',@DBH='" + edInventorySingleNum.getText().toString() + "',@Color='" +
                "" + edInventoryColor.getText().toString().trim() + "',@BoxNo='" + edInventoryBoxNum.getText().toString()
                + "',@Size='" + edInventorySize.getText().toString().trim() + "',@OutState='" + edInventoryOutState.getSelectedItem()
                + "',@OperType='StockSearch',@UserNo='" + LoginUserNo +"',@BatchID='"+BatchID+ "',@PageSize="+pageSize+",@PageIndex="+pageIndex+tj;
        ReadSQLData(sql, SEARCHSUMMAR);
    }

    private void summaryTextViewOnClick() {
        summaryLinearLayout.setVisibility(View.VISIBLE);
        detailLinearLayout.setVisibility(View.GONE);
        numberLinearLayout.setVisibility(View.GONE);
        numberListView.setVisibility(View.GONE);

        summaryTextView.setTextColor(getResources().getColor(R.color.blue));
        detailTextView.setTextColor(getResources().getColor(R.color.darkGray));
    }


//    private void detailTextViewOnClick() {
//        summaryLinearLayout.setVisibility(View.GONE);
//        detailListView.setAdapter(new LCLDetailListviewAdapter(this));
//        detailLinearLayout.setVisibility(View.VISIBLE);
//        summaryTextView.setTextColor(getResources().getColor(R.color.darkGray));
//        detailTextView.setTextColor(getResources().getColor(R.color.blue));
//    }

    private void checkNumTextViewOnClick() {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_out_bound, null);
        final PopupWindow popupWindow = new PopupWindow(view, width / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        TextView top = view.findViewById(R.id.tv_pop_top_left);
        TextView hint1 = view.findViewById(R.id.tv_pop_hint1);
        TextView hint2 = view.findViewById(R.id.tv_pop_hint2);
        TextView hint3 = view.findViewById(R.id.tv_pop_hint3);
        TextView pause = view.findViewById(R.id.tv_pop_pause);
        TextView resume = view.findViewById(R.id.tv_pop_resume);
        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        pause.setVisibility(View.GONE);
        top.setText("查询结果");
        hint1.setText("无");
        hint2.setText("xxx箱号存在xxx条码号");
        hint3.setText("xxx箱号存在xxx条码号");
        resume.setText("出库");
        resume.setOnClickListener(v -> {
            top.setText("异常操作");
            hint1.setText("该箱出库异常，请通知维修，可选择以下操作：");
            hint2.setText("a、继续等待，维修好后会自动出库，则关闭该窗口");
            hint3.setText("b、操作暂停出库，当恢复时再次操作出库");
            pause.setVisibility(View.VISIBLE);
            pause.setText("暂停出库");
            resume.setText("恢复出库");
            pause.setOnClickListener(v1 -> pause.setBackgroundResource(R.drawable.button_yellow_shape));
            resume.setOnClickListener(v1 -> pause.setBackgroundResource(R.drawable.button_primary_shape));
        });
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    private void inBoundTextViewOnClick() {
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_out_bound, null);
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        final PopupWindow popupWindow = new PopupWindow(view, width / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        TextView top = view.findViewById(R.id.tv_pop_top_left);
        TextView hint1 = view.findViewById(R.id.tv_pop_hint1);
        TextView hint2 = view.findViewById(R.id.tv_pop_hint2);
        TextView hint3 = view.findViewById(R.id.tv_pop_hint3);
        TextView pause = view.findViewById(R.id.tv_pop_pause);
        TextView resume = view.findViewById(R.id.tv_pop_resume);
        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        pause.setVisibility(View.VISIBLE);
        pause.setBackgroundResource(R.drawable.stroke_blue);
        resume.setBackgroundResource(R.drawable.stroke_blue);
        pause.setTextColor(getResources().getColor(R.color.blue));
        resume.setTextColor(getResources().getColor(R.color.blue));
        top.setText("空箱操作");
        hint1.setText("");
        hint2.setText("请选择哪种空箱入库：");
        hint3.setText("");
        pause.setText("空料箱");
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TaskId = UUID.randomUUID().toString();
                String Sql = "Exec AGV_Stock_StockCallWMS @FormType='" + FormType + "',@DepSiteNo='" + StationNo + "',@BoxNo='" + boxNumTextView.getText().toString() + "',@BoxType='入库'," +
                        "@TaskID='" + TaskId + "',@IsEmpty='1',@OperType='StockInCallWMS',@UserNo='" + LoginUserNo + "'";
                ReadSQLData(Sql, INBOUNDCHECK);
                popupWindow.dismiss();
            }
        });
        resume.setText("空料箱（含小箱）");
        resume.setOnClickListener(v -> {
            TaskId = UUID.randomUUID().toString();
            String Sql = "Exec AGV_Stock_StockCallWMS @FormType='" + FormType + "',@DepSiteNo='" + StationNo + "',@BoxNo='" + boxNumTextView.getText().toString() + "',@BoxType='入库'," +
                    "@TaskID='" + TaskId + "',@IsEmpty='0',@OperType='StockInCallWMS',@UserNo='" + LoginUserNo + "'";
            ReadSQLData(Sql, INBOUNDCHECK);
            popupWindow.dismiss();
        });
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    private void showPopupWindow(SummarzingEntity summarzingEntity) {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_out_bound, null);
        final PopupWindow popupWindow = new PopupWindow(view, width / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        TextView pause = view.findViewById(R.id.tv_pop_pause);
        TextView resume = view.findViewById(R.id.tv_pop_resume);
        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pause.setBackgroundResource(R.drawable.button_yellow_shape);
                TaskId = UUID.randomUUID().toString();
                String Sql = "EXEC AGV_Stock_StockCallWMS @DepSiteNo ='" + StationNo + "',@WMSOrderNo ='" + summarzingEntity.getWMSOrderNo()
                        + "',@OutBoxNos='" + summarzingEntity.getBoxNo() + "',@TaskID ='" + TaskId + "', @FormType='" + FormType +
                        "',@OperType='暂停出库',@UserNo='" + LoginUserNo + "'";
                ReadSQLData(Sql, STOPOUTBOUND);
                popupWindow.dismiss();
            }
        });

        resume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TaskId = UUID.randomUUID().toString();
                String Sql = "EXEC AGV_Stock_StockCallWMS @DepSiteNo ='" + StationNo + "',@WMSOrderNo ='" + summarzingEntity.getWMSOrderNo()
                        + "',@OutBoxNos='" + summarzingEntity.getBoxNo() + "',@TaskID ='" + TaskId + "', @FormType='" + FormType +
                        "',@OperType='恢复出库',@UserNo='" + LoginUserNo + "'";
                ReadSQLData(Sql, RETURNOUTBOUND);
                popupWindow.dismiss();
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    @Override
    public void OueState(int position) {
        if (summarzingEntities != null && summarzingEntities.size() > 0) {
            showPopupWindow(summarzingEntities.get(position));

        } else {
            Toaster.showLong(InventoryActivity.this, "列表为空");
        }
    }
}
